﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;

namespace YXQ.Common.Helper
{
    public static class JsHelper
    {
        /// <summary>
        /// 弹出JavaScript小窗口
        /// </summary>
        /// <param name="strMessage">提示信息</param>
        public static void Alert(Page page, string strMessage)
        {
           page.ClientScript.RegisterStartupScript(page.GetType(), "message","<script language=\"javascript\">YXQ.Common.Message(\"" + strMessage + "\");</script>");
        }


        /// <summary>
        /// 弹出JavaScript小窗口
        /// </summary>
        /// <param name="strMessage">提示信息</param>
        public static void AlertAndClose(Page page, string strMessage)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "message", "<script language=\"javascript\">YXQ.Common.Message(\"" + strMessage + "\");</script>");
        }


        /// <summary>
        /// 弹出JavaScript小窗口并重新定向到新的URL
        /// </summary>
        /// <param name="strMessage">提示信息</param>
        /// <param name="strRedirectUrl">新URL</param>
        public static void AlertAndRedirect(System.Web.UI.Page page,string strMessage, string strRedirectUrl)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "message", "<script language=\"javascript\">YXQ.Common.Message(\"" + strMessage + "\");window.location.replace('" + strRedirectUrl + "')</script>");

           // System.Web.HttpContext.Current.Response.Write(String.Format("<script language=\"javascript\">$.messager.alert('温馨提示','{0}');;window.location.replace(\"{1}\")</script>", strMessage, strRedirectUrl));
        }

        /// <summary>
        /// 重新定向到新的页面
        /// </summary>
        /// <param name="strRedirectUrl">新页面的URL</param>
        public static void Redirect(string strRedirectUrl)
        {
            System.Web.HttpContext.Current.Response.Write("<script language=\"javascript\">window.location=\"" + strRedirectUrl + "\";</script>");
        }

        public static void Redirect(string strRedirectUrl, string type)
        {
            if (type == "iframe")
                System.Web.HttpContext.Current.Response.Write(String.Format("<script language=\"javascript\">parent.location.href=\"{0}\";</script>", strRedirectUrl));
        }
        /// <summary>
        /// 根据对话框重定义到指定的页面中
        /// </summary>
        /// <param name="strMsg">信息对话框</param>
        /// <param name="TrueUrl">如果选择[是]所指向的页面地质</param>
        /// <param name="FalseUrl">如果选择[否]所指向的页面地质</param>
        public static void ConfirmGoTo(string strMsg, string TrueUrl, string FalseUrl)
        {
            System.Web.HttpContext.Current.Response.Write("<SCRIPT language=\"javascript\">");
            System.Web.HttpContext.Current.Response.Write("if (confirm(\"" + strMsg + "\"))");
            System.Web.HttpContext.Current.Response.Write("{window.location='" + TrueUrl + "';}");
            System.Web.HttpContext.Current.Response.Write("else");
            System.Web.HttpContext.Current.Response.Write("{window.location='" + FalseUrl + "';}");
            System.Web.HttpContext.Current.Response.Write("</SCRIPT>");
        }
        /// <summary>
        /// 回到历史页面
        /// </summary>
        /// <param name="iValue">-1/1</param>
        public static void GoHistory(int iValue)
        {
            System.Web.HttpContext.Current.Response.Write(String.Format("<script language=\"JavaScript\">history.go({0});</script>", iValue));
        }

        /// <summary>
        /// 关闭当前窗体
        /// </summary>
        public static void CloseWindow()
        {
            System.Web.HttpContext.Current.Response.Write("<script language=\"JavaScript\">parent.opener=null;window.close();</script>");
            System.Web.HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 刷新父窗口
        /// </summary>
        public static void RefreshParent(string url)
        {
            string js = @"<Script language='JavaScript'>
                    window.opener.location.href='" + url + "';window.close();</Script>";
            System.Web.HttpContext.Current.Response.Write(js);
        }
        /// <summary>
        /// 刷新当前窗口
        /// </summary>
        public static void Refresh()
        {
            string js = @"<Script language='JavaScript'>
                    document.location.reload();</Script>";
            System.Web.HttpContext.Current.Response.Write(js);
        }
        /// <summary>
        /// 返回值
        /// </summary>
        public static void returnValue(string bl)
        {
            System.Web.HttpContext.Current.Response.Write("<SCRIPT language=\"javascript\">");
            System.Web.HttpContext.Current.Response.Write("window.returnValue='" + bl + "';");
            System.Web.HttpContext.Current.Response.Write("</SCRIPT>");
        }

        public static bool CheckIp(string ips)
        {

            return Regex.IsMatch(ips, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
        }


        #region 获取客户端IP地址
        /// <summary>
        /// 设置IP地址
        /// </summary>
        /// <param name="strIP"></param>
        /// <returns></returns>
        private static string SetIP(string strIP)
        {
            string[] str;
            str = strIP.Split('.');
            int j;
            string tempIP = "", IP = "";
            for (int i = str.Length - 1; i >= 0; i--)
            {
                tempIP = str[i];
                if (str[i].Length < 3)
                    for (j = 1; j <= 3 - str[i].Length; j++)
                        tempIP = '0' + tempIP;
                IP = tempIP + '.' + IP;
            }
            return IP.Substring(0, IP.Length - 1);
        }

        /// <summary>
        /// 返回用户IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            return SetIP(System.Web.HttpContext.Current.Request.UserHostAddress);
        }
        #endregion

        /// <summary>
        /// 格式化字符串
        /// </summary>
        /// <param name="strText">原始字符串</param>
        /// <returns>格式化后字符串</returns>
        public static string FormatString(string strText)
        {
            strText = strText.Replace(" ", "&nbsp;&nbsp;");
            strText = strText.Replace("<", "&lt;");
            strText = strText.Replace(">", "&gt;");
            strText = strText.Replace("\n", "<br>");

            return strText;
        }

        /// <summary>
        /// 根据框架结构能来设置页面的重定向到一个新的地址
        /// </summary>
        /// <param name="Level">框架层数</param>
        /// <param name="strUrl">新网页地址</param>
        public static void RedirectParent(int Level, string strUrl)
        {
            string strLevel = "window";
            for (int i = 1; i <= Level; i++)
            {
                strLevel = strLevel + ".parent";
            }
            strLevel = strLevel + ".location='" + strUrl + "';";
            System.Web.HttpContext.Current.Response.Write("<script language=\"javascript\">" + strLevel + "</script>");
        }

        public static void ShowModalDialog(string webUrl, string webWidth, string webHeight)
        {
            string features = "dialogWidth:" + webWidth + "; dialogHeight:" + webHeight + "; status:0; help:0";
            System.Web.HttpContext.Current.Response.Write("<script language=\"javascript\">showModalDialog(\"" + webUrl + "\",\"window\",\"" + features + "\");</script>");
        }

        /// <summary>
        /// 打开指定大小的新窗体
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="width">宽</param>
        /// <param name="heigth">高</param>
        /// <param name="top">头位置</param>
        /// <param name="left">左位置</param>
        public static void OpenWebFormSize(string url, int width, int heigth, int top, int left)
        {
            string js = @"<Script language='JavaScript'>window.open('" + url + @"','','height=" + heigth + ",width=" + width + ",top=" + top + ",left=" + left + ",location=no,menubar=no,resizable=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,directories=no');</Script>";
            System.Web.HttpContext.Current.Response.Write(js);
        }

        #region 截取字符串操作函数
        /// <summary>
        /// 截取字符串，保留其HTML格式
        /// </summary>
        /// <param name="strText"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string Cut(string strText, int len)
        {
            if (strText.Length > len)
            {
                return strText.Substring(0, len) + "…";
            }
            else
            {
                return strText;
            }
        }

        private static string LoseHtml(string ContentStr)
        {
            string ClsTempLoseStr = "";
            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex("<\\/*[^<>]*>");
            ClsTempLoseStr = regEx.Replace(ContentStr, "");
            return ClsTempLoseStr;
        }

        /// <summary>
        /// 截取字符串去掉其HTML字符
        /// </summary>
        /// <param name="inputString"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string ToCut(string inputString, int len)
        {
            int tempLen = 0;
            string tempString = "";
            inputString = LoseHtml(inputString);
            ASCIIEncoding ascii = new ASCIIEncoding();

            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }

                try
                {
                    tempString += inputString.Substring(i, 1);
                }
                catch
                {
                    break;
                }

                if (tempLen > len)
                    break;
            }
            //如果截过则加上半个省略号
            byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
            if (mybyte.Length > len)
                tempString = tempString.Substring(0, tempString.Length - 3 == 0 ? 1 : tempString.Length - 3) + "…";

            return tempString;
        }
        #endregion

        /// <summary>
        /// 获得关键字
        /// </summary>
        /// <param name="strHeard">字符前字</param>
        /// <returns>系统关键字</returns>
        public static string GetPrimaryKey(string strHeard)
        {
            string strKey = DateTime.Now.ToString("yyMMddhhmmss");
            strKey = strKey + DateTime.Now.Millisecond.ToString();
            Random Ran = new Random();
            strKey = strHeard + strKey + Ran.Next(1, 99999);
            return strKey;
        }

        /// <summary>
        /// 检查 Request.QueryString的值。
        /// </summary>
        /// <param name="QuseryStringKey">QueryString的值</param>
        public static void AlertQueryString(string QuseryStringKey)
        {
            HttpContext r = HttpContext.Current;
            if (r.Request.QueryString[QuseryStringKey] == null)
            {
                r.Response.Write("<script>alert('访问缺乏系统参数!');history.go(-1);</script>");
                r.Response.End();
            }
            else
            {
                if (!StringUtils.IsNumeric(r.Request.QueryString[QuseryStringKey]))
                {
                    r.Response.Write("<script>alert('造访被系统拒绝!');history.go(-1);</script>");
                    r.Response.End();
                }
            }
        }
    }
}

